package com.annhoa.infrastructure.interceptor;


import com.alibaba.fastjson.JSON;
import com.annhoa.infrastructure.common.AjaxResult;
import com.annhoa.infrastructure.util.ServletUtils;
import com.annhoa.infrastructure.util.StringUtils;
import com.annhoa.infrastructure.util.aes.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.TreeMap;

/**
 * @author wanglulei
 * @create 2019-03-27 16:47
 * @desc 验签拦截器
 **/
@Slf4j
public class SignatureInInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String appKey = request.getHeader("appKey");
        String signature = request.getHeader("signature");
        if (StringUtils.isEmpty(appKey) || StringUtils.isEmpty(signature)) {
            log.debug("appKey/signature不能为空...........");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error("appKey/signature为空")));
        }
        String timestamp = request.getHeader("timestamp");
        if (StringUtils.isEmpty(timestamp)) {
            log.debug("timestamp不能为空...........");
            response.setStatus(HttpStatus.SC_BAD_REQUEST);
            ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error("timestamp为空")));
        }
        String method = request.getMethod();
        if (method.equalsIgnoreCase("post")){
            boolean json = SignUtil.isJson(request);
            if (!json) {
                ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error("不支持请求方式")));
            }
            SignUtil.verifySign(SignUtil.getBodyString(request), appKey, timestamp, signature);
        }else {
            TreeMap<String, String> params = new TreeMap<>();
            Enumeration<String> enu = request.getParameterNames();
            while (enu.hasMoreElements()) {
                String paramName = enu.nextElement().trim();
                params.put(paramName, URLDecoder.decode(request.getParameter(paramName), "UTF-8"));
            }
            try {
                SignUtil.verifySign(params.toString(), appKey, timestamp, signature);
            }catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }
        }
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        // 在处理过程中，执行拦截
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        // 执行完毕，返回前拦截
    }
}
